package cc.android.testapp.ui.part;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;

import cc.android.testapp.R;
import cc.android.testapp.ui.inject.InjectView;
import cc.android.testapp.ui.inject.ViewInject;
import cc.android.testapp.util.CTool;
import cc.commons.util.StringUtil;

public class HisEditText extends FrameLayout implements View.OnClickListener {

    protected int mHisLimit = 10;
    protected String mCfgNode = "unknown";
    @InjectView(id = R.id.et_his_input)
    public EditText mETInput;
    @InjectView(id = R.id.btn_his_more, addClickListener = true)
    public Button mBtnMore;
    public final ArrayList<String> mHistroy = new ArrayList<>();
    protected ArrayAdapter<String> mHisAdapter;

    public HisEditText(Context context, AttributeSet pAttrs) {
        super(context, pAttrs);

        LayoutInflater inflater = LayoutInflater.from(context);
        View tContent = inflater.inflate(R.layout.his_edit_text, null);
        this.addView(tContent);
        onCreate(pAttrs);
    }

    protected void onCreate(AttributeSet pAttrs) {
        ViewInject.injectView(this, this::findViewById, this);

        TypedArray tTr = this.getContext().obtainStyledAttributes(pAttrs, R.styleable.HisEditText);
        this.setHint(tTr.getString(R.styleable.HisEditText_hint));
        this.setCfgNode(tTr.getString(R.styleable.HisEditText_cfg_node));
        this.mHisLimit = tTr.getInt(R.styleable.HisEditText_his_limit, this.mHisLimit);
        tTr.recycle();

        mHisAdapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_item, this.mHistroy) {

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                if (view instanceof TextView) {
                    TextView tTV = (TextView) view;
                    String tText = tTV.getText().toString();
                    int display = CTool.calculateMaxChars(tText, tTV.getTextSize(), mETInput.getWidth());
                    if (display != tTV.length()) {
                        tText = tText.substring(tText.length() - display);
                        tTV.setText(tText);
                    }
                }
                return view;
            }
        };
    }

    public HisEditText setCfgNode(String pNode) {
        if (StringUtil.isNotEmpty(pNode)) this.mCfgNode = pNode;
        return this;
    }

    public String getCfgNode() {
        return this.mCfgNode;
    }

    public HisEditText setHint(String pHint) {
        this.mETInput.setHint(pHint);
        return this;
    }

    public HisEditText setHistroy(Collection<String> pHis) {
        this.mHistroy.clear();
        this.mHistroy.addAll(pHis);
        this.mHisAdapter.notifyDataSetChanged();
        return this;
    }

    public HisEditText setText(String pText) {
        this.mETInput.setText(pText);
        pushToHistroy();
        return this;
    }

    public void pushToHistroy() {
        String tText = this.mETInput.getText().toString();
        if (StringUtil.isBlank(tText)) return;

        this.mHistroy.remove(tText);
        this.mHistroy.add(0, tText);
        while (this.mHistroy.size() > this.mHisLimit)
            this.mHistroy.remove(this.mHistroy.size() - 1);
        this.mHisAdapter.notifyDataSetChanged();
    }


    public CharSequence getText() {
        return this.mETInput.getText();
    }

    public HisEditText loadFromJson(JSONObject pCfg) {
        this.mETInput.setText(pCfg.optString(this.getCfgNode(), ""));
        this.mHistroy.clear();
        JSONArray pHis = pCfg.optJSONArray(this.getCfgNode() + "_his");
        if (pHis != null) {
            for (int i = 0; i < pHis.length(); i++) {
                try {
                    this.mHistroy.add(String.valueOf(pHis.get(i)));
                } catch (Throwable ignored) {
                }
            }
        }
        this.mHisAdapter.notifyDataSetChanged();
        return this;
    }

    public HisEditText saveToJson(JSONObject pCfg) throws JSONException {
        String tText = this.getText().toString();
        pCfg.put(this.getCfgNode(), tText);

        pCfg.put(this.getCfgNode() + "_his", new JSONArray(this.mHistroy));
        return this;
    }

    @Override
    public void onClick(View v) {
        if (v == mBtnMore) {
            ListView tLV = new ListView(this.getContext());
            tLV.setAdapter(this.mHisAdapter);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                tLV.setBackgroundColor(Color.argb(0.8F, 1, 1, 1));
            }
            tLV.setDivider(new ColorDrawable(Color.TRANSPARENT));
            tLV.setDividerHeight(20);
            PopupWindow popup = new PopupWindow(tLV, this.mETInput.getWidth(), 400);
            popup.setOutsideTouchable(true);
            popup.showAsDropDown(this.mETInput);

            tLV.setOnItemClickListener((parent, view, position, id) -> {
                this.mETInput.setText(mHisAdapter.getItem(position));
                popup.dismiss();
            });
        }
    }
}
